#!/usr/bin/env python
# encoding: utf-8

Import('env')
Import('VERSION_MAJOR')
Import('VERSION_MINOR')
Import('VERSION_PATCH')
Import('create_uninstall_target')
Import('find_sphinx_binary')


import os
import time
import subprocess

from functools import partial


def run_sphinx_binary(builder, **kwargs):
    sphinx_binary = find_sphinx_binary()
    if sphinx_binary is None:
        return

    build_dir = os.path.join('docs/_build', builder)
    try:
        os.makedirs(build_dir)
    except OSError:
        pass

    subprocess.check_call(
        [sphinx_binary, '-Q', '-b', builder, 'docs', build_dir]
    )

# Do not use partial(), but a real function.
# Scons uses this to check if the previous action
# differs from the current action.
# Partial actions are always different.
def run_sphinx_binary_man(**kwargs):
    run_sphinx_binary('man', **kwargs)


manpage = env.Command(
    '_build/man/rmlint.1', 'rmlint.1.rst',
    env.Action(run_sphinx_binary_man, "Building manpage from rst...")
)

env.Default(manpage)

env.Alias('man', manpage)


if 'install' in COMMAND_LINE_TARGETS:
    man_install = env.InstallPerm(
        '$PREFIX/share/man/man1',
        [manpage],
        int("644", 8),
    )
    target = env.Alias('install', [manpage, man_install])


if 'uninstall' in COMMAND_LINE_TARGETS:
    create_uninstall_target(env, '$PREFIX/share/man/man1/rmlint.1')

if 'docs' in COMMAND_LINE_TARGETS:
    env.Alias('docs',
        env.Command(
            'make_docs', None,
            Action(partial(run_sphinx_binary, 'html'), "Building online docs...")
        ),
    )
